package com.gitee.wsl.collections.bean

import com.gitee.wsl.base.Objects
import com.gitee.wsl.collections.iterator.api.MutableMapEntry

/**
 * HashEntry used to store the data.
 *
 *
 * If you subclass `AbstractHashedMap` but not `HashEntry`
 * then you will not be able to access the protected fields.
 * The `entryXxx()` methods on `AbstractHashedMap` exist
 * to provide the necessary access.
 *
 *
 * @param <K> the type of the keys
 * @param <V> the type of the values
</V></K> */
open class HashEntry<K, V>(
    /** The key  */
    override var key: K,
    override var value: V,
    /** The hash code of the key  */
    var hashCode: Int = key.hashCode() + value.hashCode(),
    /** The next entry in the hash chain  */
    var next: HashEntry<K, V>? = null,
) : MutableMapEntry<K,V> {

    /** The value  */

    override fun equals(other: Any?): Boolean {
        if (other === this) {
            return true
        }
        if (other !is Map.Entry<*, *>) {
            return false
        }
        val other = other as Map.Entry<*, *>
        return Objects.equals(key, other.key) &&
                Objects.equals(value, other.value)
    }

    override fun hashCode(): Int {
        return (key?.hashCode() ?: 0) xor (value?.hashCode() ?: 0)
    }

    override fun toString(): String {
        return StringBuilder().append(key).append('=').append(value).toString()
    }

    override fun setValue(newValue: V): V {
        val old = value
        value = newValue
        return old
    }
}